package com.zjf.carpark.shiro;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * shiro配置类
 * @Author: zhangjf
 * @Date: 2020/5/10
 */
//@Configuration
public class ShiroConfig {

    /**
     * 创建ShiroFilterFactoryBean
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        // 设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        // 添加Shiro内置过滤器
        /**
         * shiro内置过滤器，
         * anno：无需认证访问
         * authc：必须认证才可以访问
         * user:
         */
        Map<String,String> filterMap = new LinkedHashMap<>();
        filterMap.put("/desk/parkPlace", "anon");
        filterMap.put("/desk/barChart", "anon");
        filterMap.put("/desk/announcement", "anon");
        filterMap.put("/desk/advise", "anon");
        filterMap.put("/parkPlace/selectAllParkPlace", "anon");
        filterMap.put("/announcement/showAllRelease", "anon");
        filterMap.put("/desk/oneAnnouncement", "anon");
        filterMap.put("/announcement/showOne", "anon");
        filterMap.put("/weiXin/login", "anon");
        filterMap.put("/desk/ownerLogin", "anon");
        filterMap.put("/user/checkCode", "anon");
        filterMap.put("/user/login", "anon");

        filterMap.put("/desk/*", "authc");

        //
        shiroFilterFactoryBean.setLoginUrl("/desk/login");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);

        return shiroFilterFactoryBean;
    }
    /**
     * 创建DefaultWebSecurityManager
     */
    @Bean( name = "securityManager" )
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager =  new DefaultWebSecurityManager();
        // 关联Realm
        securityManager.setRealm(userRealm);
        return securityManager;
    }
    /**
     * 创建Realm
     */
    @Bean(name = "userRealm")
    public UserRealm getRealm(){
        return new UserRealm();
    }
}
